import { Plugin } from '@nuxt/types'
import { NuxtAxiosInstance } from '@nuxtjs/axios'

import userModule from '@/api/user'

const apiMap = ($axios: NuxtAxiosInstance) => ({
    user: userModule($axios),
})

type ApiType = ReturnType<typeof apiMap>

declare module 'vue/types/vue' {
    interface Vue {
        $api: ApiType
    }
}

declare module '@nuxt/types' {
    interface Context {
        $api: ApiType
    }
}

declare module 'vuex/types/index' {
    interface Store<S> {
        $api: ApiType
    }
}

// https://axios.nuxtjs.org/extend
// https://typescript.nuxtjs.org/zh-hant/cookbook/plugins/
const axiosPlugin: Plugin = ({ $axios, redirect }, inject) => {
    $axios.onRequest((config) => {
        console.log('Making request to ' + config.url)
    })

    $axios.onError((error: any) => {
        const code = parseInt(error.response && error.response.status)
        if (code === 400) {
            redirect('/400')
        }
    })

    // Inject to context as $api
    inject('api', apiMap($axios))
}

export default axiosPlugin
